package com.jash.rxandroiddemo;

import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ListViewCompat;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {

    private ImageView image;
    private ArrayAdapter<Object> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView list = (ListView) findViewById(R.id.main_list);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<>());
        list.setAdapter(adapter);
        Observable.just("http://api.meishi.cc/v5/buy_index1.php?format=json")
                .observeOn(Schedulers.io())
                .map(s -> {
                    try {
                        return new URL(s).openConnection().getInputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                })
                .map(InputStreamReader::new)
                .map(reader -> new Gson().fromJson(reader, Map.class))
                .flatMap(map -> Observable.from((List)map.get("end_list")))
                .map(o -> (String)((Map)o).get("title"))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(adapter::add);

//        image = (ImageView) findViewById(R.id.main_image);
//        Observable.just("http://www.inexus.co/template/inx/src/img/logo.png")
//                .observeOn(Schedulers.io())
//                .map(s -> {
//                    try {
//                        return new URL(s).openConnection().getInputStream();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    return null;
//                })
//                .map(BitmapFactory::decodeStream)
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(image::setImageBitmap);
    }
}
